package boot.spring.scheduler;

import boot.spring.service.DorisTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
@Slf4j
public class TableCacheScheduler {
    @Autowired
    private DorisTableService tableService;

    @Value("${cache-dbs:}")
    private List<String> cacheDbs;

    /**
     * 首次执行标识，防止与 ApplicationRunner 重复执行
     */
    private static final AtomicBoolean INIT_DONE = new AtomicBoolean(false);

    @Scheduled(fixedRate = 10 * 60 * 1000) // 每10分钟刷新一次缓存
    public void refreshAllTableCache() {
        if (INIT_DONE.compareAndSet(false, true)) {
            log.info("[初始化] 第一次加载表缓存...");
        } else {
            log.info("[定时任务] 刷新表缓存...");
        }
        if (cacheDbs != null) {
            cacheDbs.forEach(dbName -> {
                tableService.loadTableNames(dbName);
            });
        }
    }
}